<template>
   <van-form @submit="nextHandler" validate-trigger="onChange">
      <van-cell-group inset>
         <van-field v-model="code" name="code" label="请输入验证码" :rules="[
         { required: true,pattern, message: '验证码必须是5位数字' },]" label-width="6em">
            <template #button>
               <van-button size="small" type="primary" :disabled="sendDisable" @click="sendCodeHandler">{{buttonText}}
               </van-button>
            </template>
         </van-field>

      </van-cell-group>
      <div style="margin: 16px;">
         <van-button round block type="danger" native-type="submit" :disabled="disable">
            下一步
         </van-button>
      </div>
   </van-form>
</template>

<script setup lang='ts'>
import { ref, computed, reactive, onMounted, onBeforeUnmount } from 'vue';
import { sendMsgCode, checkCode } from '@/apis/user'
import { useUserStore } from '@/store/userStore'
import { useRouter } from 'vue-router'
import { Notify } from 'vant'
const user = useUserStore()
const code = ref('')
const router = useRouter()
//正则校验
const pattern = /^\d{5}$/
// 下一步按钮是否禁用
const disable = computed(() => {
   return !pattern.test(code.value)
})
//记录还有多少秒可以发送验证码
const second = ref(0)
//设置一个定时器
let timerId: number | null = null
//记录正确的验证码
let trueCode = ''
//定时器的回调函数
const sendCutFn = () => {
   second.value--
   //实时记录现在的时间戳和剩余秒数
   localStorage.setItem('second', second.value.toString())
   localStorage.setItem('lastTime',(new Date().getTime()/1000).toString())
   if (second.value <= 0) {
      //清空本地存储
      localStorage.removeItem('second')
      localStorage.removeItem('lastTime')
      clearInterval(timerId)
   }
}
//点击发送验证码处理函数
const sendCodeHandler = () => {
   //调用接口获取验证码
   sendMsgCode(user.tel)
      .then(res => {
         console.log(res.data);


      })
   //点击按钮，剩余秒数变成60
   second.value = 60
   timerId = setInterval(sendCutFn, 100)
}

// 下一步按钮是否禁用
const sendDisable = computed(() => {
   return second.value <= 0 ? false : true
})
//发送验证码按钮要显示的文字
const buttonText = computed(() => {
   return second.value <= 0 ? '发送验证码' : `${second.value}s发送验证码`
})
const nextHandler = () => {
   checkCode(user.tel, code.value)
      .then(res => {
         if ((res as any).code === '200') {
            router.push('/register/stepThree');
         } else {
            // 验证码错误，提示验证码错误
            Notify({ type: 'danger', message: '验证码错误' })
         }

      })
}
//当前页面打开，如果剩余时间>0，继续计数
const nowTime = parseInt(new Date().getTime() / 1000 as any) //当前时间戳
const lastTime = parseInt(localStorage.getItem('lastTime'))//上次离开的时间戳，单位S
const lastSecond =parseInt(localStorage.getItem('second'))
// 如果本地存储有lastTime和lastSecond，说明上次倒计时没有结束
onMounted(() => {
   if (lastTime && lastSecond) {
      if (nowTime - lastTime < lastSecond) {
         //如果过去的秒小于剩余的秒
         second.value = lastSecond - (nowTime - lastTime)
         timerId=setInterval(sendCutFn,1000)
      }
   }
})

//组件离开的时候，清除定时器 
onBeforeUnmount(() => {
   clearInterval(timerId)
})

</script>

<style scoped lang='scss'>
.van-form {
   padding-top: 25px;
}
</style>
